package handler

import (
	"fmt"
	"choujiang/box_server/service"
	"choujiang/common/consts"
	"choujiang/common/models"
	"choujiang/common/utils"
	"regexp"
	"strconv"

	"github.com/gin-gonic/gin"
)

func AddressUpdate(c *gin.Context) {
	form := c.Request.Form
	province := form.Get("province")
	city := form.Get("city")
	area := form.Get("area")
	uniqueId := form.Get("uniqueId")
	receiver := form.Get("receiver")
	phone := form.Get("phone")
	address := form.Get("address")
	int64Province, _ := strconv.ParseInt(province, 10, 64)
	int64City, _ := strconv.ParseInt(city, 10, 64)
	int64Area, _ := strconv.ParseInt(area, 10, 64)
	user := model.GetUserByUniqueId(uniqueId)
	if user == nil {
		utils.Error(consts.ErrUserNotFound, c)
		return
	}
	if receiver == "" || phone == "" || int64Province == 0 || int64City == 0 {
		utils.Error(consts.ErrUserAddressNotEnough, c)
		return
	}
	if !validatePhone(phone) {
		utils.Error(consts.ErrInvalidPhone, c)
		return
	}

	err := service.UpdateUserAddress(receiver, phone, int64Province, int64City, int64Area, address, user.Id)
	if err != nil {
		fmt.Printf("service.AddressAdd err:", err)
	}

	utils.JSON("ok", c)
}

func AddressGet(c *gin.Context) {
	form := c.Request.Form
	uniqueId := form.Get("uniqueId")
	user := model.GetUserByUniqueId(uniqueId)
	if user == nil {
		utils.Error(consts.ErrUserNotFound, c)
		return
	}
	address, err := service.GetUserAddress(user.Id)
	if err != nil {
		fmt.Printf("service.AddressGet err:", err)
	}
	utils.JSON(address, c)
}

func validatePhone(mobileNum string) bool {
	var regular = "^(13[0-9]|14[57]|15[0-35-9]|18[07-9])\\d{8}$"
	reg := regexp.MustCompile(regular)
	return reg.MatchString(mobileNum)
}
